'use client';

import React, {useEffect, useState} from 'react';
import {SubmitHandler, useForm} from 'react-hook-form';
import FormInput from "@/components/ui/Forms/FormElements/FormInput";
import FormSelect from "@/components/ui/Forms/FormElements/FormSelect";
import Button from "@/components/ui/Button/Button";
import {deleteObj, getObjWithoutToken} from "@/services/api_service";
import {createPayment} from "@/services/payment_service";
import Script from "next/script";
import styles from './TicketForm.module.css';
import TicketQr from "@/components/ui/TicketQr/TicketQr";

declare global {
    interface Window {
        YooMoneyCheckoutWidget: any;
    }
}

type TypeTicketFormInputs = {
    ticket_type: string;
    route: string;
    registration_number?: string;
    vehicle_type?: string;
    vehicle_id?: string;
};

type TypeTicketData = {
    ticket_type: string;
    route: string;
    vehicle?: {
        registration_number: string;
        vehicle_type: string;
        length: number;
        weight: number;
    }
    vehicle_id?: string;
} & TypeTicketFormInputs;

type TypeVehicleOption = {
    value: string;
    label: string;
};

type TypeTicketTypeOption = {
    id: string;
    value: string;
    label: string;
    cost: number;
};

type TypeRouteOption = {
    value: string;
    label: string;
};

type TicketFormProps = {
    setModalOpen: React.Dispatch<React.SetStateAction<boolean>>;
    setBuyTicketQr?: React.Dispatch<React.SetStateAction<boolean>>
    vehicleOptions?: TypeVehicleOption[];
    showVehicleOptions: boolean;
    showQrCode: boolean;
};

const vehicleTypeOptions = [
    {value: 'car_3m_3.5w', label: 'Мотоцикл'},
    {value: 'car_6m_3.5w', label: 'Легковая'},
    {value: 'car_6m_6w', label: 'Грузовик'},
    {value: 'car_12m_8w', label: 'Прицеп'},
];

const TicketForm = ({
                        setModalOpen,
                        setBuyTicketQr,
                        vehicleOptions = [],
                        showVehicleOptions,
                        showQrCode
                    }: TicketFormProps) => {
    const [withTransport, setWithTransport] = useState(showVehicleOptions);
    const [isSuccess, setIsSuccess] = useState(false);
    const [qrCodeUrl, setQrCodeUrl] = useState<string | null>(null);
    const [ticketId, setTicketId] = useState<string | null>(null);
    const [paymentToken, setPaymentToken] = useState<string | null>(null);
    const [ticketTypeOptions, setTicketTypeOptions] = useState<TypeTicketTypeOption[]>([]);
    const [routeOptions, setRouteOptions] = useState<TypeRouteOption[]>([]);

    const {
        register,
        handleSubmit,
        formState: {errors},
    } = useForm<TypeTicketFormInputs>();


    // Запрос типов билетов из базы данных
    useEffect(() => {

        const fetchTicketTypes = async () => {
            try {
                const ticketTypes = await getObjWithoutToken('/api/ships/ticket-types/');
                setTicketTypeOptions(ticketTypes.map((type: any) => ({
                    id: type.id,
                    value: type.name,
                    label: `${type.name} (₽${type.cost})`,
                    cost: type.cost,
                })));
            } catch (error) {
                console.error('Ошибка при получении типов билетов:', error);
            }
        };
        fetchTicketTypes();

        const fetchRoutes = async () => {
            try {
                const routes = await getObjWithoutToken('/api/planning/routes/');
                setRouteOptions(routes.map((route: any) => ({
                    value: route.id,
                    label: `${route.departure_port.name} - ${route.arrival_port.name}`,
                })));
            } catch (error) {
                console.error('Ошибка при получении списка маршрутов:', error);
            }
        };

        fetchRoutes();
    }, []);


    const onSubmit: SubmitHandler<TypeTicketData> = async (data: TypeTicketData) => {
        try {
            const selectedTicketTypeOption = ticketTypeOptions.find(option => option.value === (!showVehicleOptions ? data.ticket_type : "Одноразовый"));
            const amount = selectedTicketTypeOption!.cost;

            if (data.vehicle_type) {
                const match = data.vehicle_type.match(/(\d+(?:\.\d+)?)m_(\d+(?:\.\d+)?)w/);
                data.vehicle = {
                    registration_number: data.registration_number!.toUpperCase(),
                    vehicle_type: vehicleTypeOptions.find(option => option.value === data.vehicle_type)?.label || '',
                    length: parseFloat(match![1]),
                    weight: parseFloat(match![2]),
                };
            }

            const ticketResponse = await createPayment({
                ticket_type: selectedTicketTypeOption!.id,
                ticket_type_name: selectedTicketTypeOption!.value,
                route_id: data.route,
                vehicle: data.vehicle,
                vehicle_id: data.vehicle_id,
                amount,
            }, showVehicleOptions ? 'withToken' : 'noToken');

            setTicketId(ticketResponse.ticket_id);
            setPaymentToken(ticketResponse.payment_token);
        } catch (error) {
            console.error('Ошибка при оплате билета:', error);
        }
    };

    useEffect(() => {
        if (paymentToken) {
            const checkout = new window.YooMoneyCheckoutWidget({
                confirmation_token: paymentToken,
                customization: {
                    modal: true,
                },
                error_callback: (error: any) => console.error('Ошибка оплаты:', error),
            });

            checkout.on('modal_close', async () => {
                try {
                    if (ticketId) {
                        await deleteObj(`/api/tickets/${ticketId}/`);
                        setTicketId(null);
                    }
                } catch (error) {
                    console.error('Ошибка при удалении временного билета:', error);
                }
                checkout.destroy();
            });

            checkout.on('success', async () => {
                setIsSuccess(true);
                !showVehicleOptions && setModalOpen(false);
                checkout.destroy();
            });

            checkout.render();
        }
    }, [paymentToken]);

    useEffect(() => {
        let intervalId: NodeJS.Timeout;

        if (isSuccess && showQrCode) {
            intervalId = setInterval(async () => {
                try {
                    const qrCodeResponse = await getObjWithoutToken(`/api/ships/tickets/${ticketId}/qr-code/`);
                    setQrCodeUrl(qrCodeResponse.qr_code_url);

                    if (qrCodeResponse.qr_code_url) {
                        setBuyTicketQr && setBuyTicketQr(true)
                        setIsSuccess(false);
                    }
                } catch (error) {
                    console.error('Ошибка при получении QR-кода:', error);
                }
            }, 4000);
        }

        return () => {
            if (intervalId) {
                clearInterval(intervalId);
            }
        };
    }, [isSuccess, showQrCode]);

    if (qrCodeUrl) {
        return (
            <TicketQr qrCodeUrl={qrCodeUrl}/>
        );
    }

    return (
        <>
            <Script
                src="https://yookassa.ru/checkout-widget/v1/checkout-widget.js"
                strategy="lazyOnload"
            />
            {!isSuccess ?
                <form onSubmit={handleSubmit(onSubmit)} className={styles.formWrapper}>
                    <div className={styles.inputs_container}>
                        {!showVehicleOptions &&
                            <FormSelect<TypeTicketFormInputs>
                                id="ticket_type"
                                name="ticket_type"
                                label="Выберите тип билета"
                                options={ticketTypeOptions.map(option => ({
                                    value: option.value,
                                    label: option.label
                                }))}
                                register={register}
                                rules={{required: "Тип билета обязателен"}}
                                errors={errors}
                            />
                        }
                        <FormSelect<TypeTicketFormInputs>
                            id="route"
                            name="route"
                            label="Выберите маршрут"
                            options={routeOptions}
                            register={register}
                            rules={{required: "Маршрут обязателен"}}
                            errors={errors}
                        />
                        {withTransport && showVehicleOptions && (
                            <>
                                <FormInput<TypeTicketFormInputs>
                                    id="registration_number"
                                    type="text"
                                    name="registration_number"
                                    kind="registration_number"
                                    label="Введите номер ТС"
                                    mask="****** 999"
                                    placeholder="AA000A 72"
                                    register={register}
                                    rules={{
                                        required: "Номер транспорта обязателен",
                                        minLength: {
                                            value: 9,
                                            message: "Введите все символы номера"
                                        }
                                    }}
                                    errors={errors}
                                />
                                <FormSelect<TypeTicketFormInputs>
                                    id="vehicle_type"
                                    name="vehicle_type"
                                    label="Выберите тип ТС"
                                    options={vehicleTypeOptions}
                                    register={register}
                                    rules={{required: "Тип транспорта обязателен"}}
                                    errors={errors}
                                />
                            </>
                        )}
                        {!showVehicleOptions && vehicleOptions.length > 0 && (
                            <FormSelect<TypeTicketFormInputs>
                                id="vehicle_id"
                                name="vehicle_id"
                                label="Выберите транспортное средство"
                                options={vehicleOptions}
                                register={register}
                                rules={{required: "Выберите транспортное средство"}}
                                errors={errors}
                            />
                        )}
                    </div>
                    <div className={styles.buttons_container}>
                        <Button type="submit" kind="submit" content="Оплатить"/>
                        {showVehicleOptions && (
                            <Button type="button" kind="secondary"
                                    content={withTransport ? "У меня нет транспорта" : "У меня есть транспорт"}
                                    onClick={() => setWithTransport(!withTransport)}/>
                        )}
                    </div>
                </form>
                :
                <div className={styles.QrContainer}>
                    <div className={styles.load}>
                        <hr/>
                        <hr/>
                        <hr/>
                        <hr/>
                    </div>
                </div>}
        </>
    );
};

export default TicketForm;
